<template>
    <d2-container class="warning-header">
        <el-card>
            <el-row :gutter="20">
                <el-form :inline="true" :model="formInline" class="demo-form-inline">
                    <el-form-item label="项目名称">
                        <el-input v-model="formInline.projectName" style="width:140px"></el-input>
                    </el-form-item>
                    <el-form-item label="所属区域">
                        <el-select v-model="formInline.province" @change="handleProvinceSelect" placeholder="请选择省"
                                   style="width:180px;padding-right: 20px;">
                            <el-option v-for="(item,index) in provices" :key="index" :label="item.name"
                                       :value="item.name"></el-option>
                        </el-select>
                        <el-select v-model="formInline.city" @change="handleCitySelect" placeholder="请选择市"
                                   style="width:180px;padding-right: 20px;">
                            <el-option v-for="(item,index) in citys " :key="index" :label="item.name"
                                       :value="item.name"></el-option>
                        </el-select>
                        <el-select v-model="formInline.zone" placeholder="请选择县/区"
                                   style="width:180px;padding-right: 20px;">
                            <el-option v-for="(item,index) in districts " :key="index" :label="item.name"
                                       :value="item.name"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="地址">
                        <el-input v-model="formInline.address" style="width:140px"></el-input>
                    </el-form-item>
                    <el-form-item label="所属业主">
                        <el-input v-model="formInline.owner" style="width:140px"></el-input>
                    </el-form-item>
                    <el-form-item label="设备编码">
                        <el-input v-model="formInline.DeviceNo" style="width:140px"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <template slot-scope="scope">
                            <el-button icon="el-icon-search" size="mini" round @click="onSubmit" type="primary">搜索
                            </el-button>
                            <el-button round type="primary" size="mini" @click="createProject">
                                创建项目
                            </el-button>
                        </template>
                    </el-form-item>
                </el-form>
            </el-row>
        </el-card>
        <br/>
        <div>
            <el-card>
                <el-table
                        :data="tableData.data"
                        :stripe="true"
                        :border="true"
                        tooltip-effect="dark">
                    <el-table-column type="index" width="50" label="序号" align="center"></el-table-column>
                    <el-table-column prop="projectName" label="项目名称" width="180px" align="center">
                    </el-table-column>
                    <el-table-column prop="username" label="项目所有者" width="180px" align="center">
                    </el-table-column>
                    <el-table-column prop="country" label="国家" width="100px" align="center">
                    </el-table-column>
                    <el-table-column prop="province" label="省" width="100px" align="center">
                    </el-table-column>
                    <el-table-column prop="city" label="市" width="100px" align="center">
                    </el-table-column>
                    <el-table-column prop="zone" label="区" width="100px" align="center">
                    </el-table-column>
                    <el-table-column prop="address" label="详细地址" width="180px" align="center">
                    </el-table-column>
                    <el-table-column prop="manager" label="联系人" width="120px" align="center">
                    </el-table-column>
                    <el-table-column prop="phone" label="联系电话" width="120px" align="center">
                    </el-table-column>
                    <el-table-column prop="img" label="项目图片" width="120px" align="center">
                    </el-table-column>
                    <el-table-column prop="lat" label="经度" width="180px" align="center">
                    </el-table-column>
                    <el-table-column prop="lng" label="纬度" width="180px" align="center">
                    </el-table-column>
                    <el-table-column label="操作" width="350px" fixed="right" align="center">
                        <template slot-scope="scope">
                            <el-button @click="edit(scope.$index,scope.row)" size="mini" round class="minis"
                                       icon="el-icon-edit">编辑
                            </el-button>
                            <el-button @click="addDevice(scope.$index,scope.row)" size="mini" round class="minis"
                                       icon="el-icon-edit">设备
                            </el-button>
                            <el-button @click="onContact(scope.$index,scope.row)" size="mini" round class="minis"
                                       icon="el-icon-edit">联系人
                            </el-button>
                            <el-button @click="handleDelete(scope.$index,scope.row)" size="mini" round class="minis"
                                       icon="el-icon-delete" type="danger">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>
        <!--分页操作 -->
        <template slot="footer">
            <div class="block">
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page.sync="currentPage"
                        layout="prev, pager, next, jumper"
                        :total="tableData.total">
                </el-pagination>
            </div>
        </template>
        <!-- 管理设备分页-->
        <el-dialog
                title="项目信息"
                :visible.sync="editFormVisible"
                width="35%"
                :before-close="handleClose">
            <el-card>
                <el-form :inline="true" :model="detailData" class="demo-form-inline" ref="detailData">
                    <el-form-item label="所属业主" prop="username">
                        <el-select v-model="detailData.username" style="width:180px;padding-right: 20px;">
                            <el-option v-for="(item,index) in username" :key="index" :label="item.Id"
                                       :value="item.username"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="项目名称" prop="projectName">
                        <el-input v-model="detailData.projectName" auto-complete="off" placeholder="请输入项目名称"
                                  style="width:180px"></el-input>
                    </el-form-item>
                    <el-form-item label="国家" prop="country">
                        <el-select v-model="detailData.country" placeholder="请选择国家"
                                   style="width:180px;padding-left: 28px;">
                            <el-option label="请选择国家" value="0"></el-option>
                            <el-option label="中国" value="中国"></el-option>
                            <el-option label="日本" value="日本"></el-option>
                            <el-option label="非洲" value="非洲"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="省" style="padding-left: 28px;">
                        <el-select v-model="detailData.province" @change="handleProvinceSelect" placeholder="请选择省"
                                   style="width:180px;padding-left: 33px;">
                            <el-option v-for="(item,index) in provices" :key="index" :label="item.name"
                                       :value="item.name"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="市">
                        <el-select v-model="detailData.city" @change="handleCitySelect" placeholder="请选择市"
                                   style="width:180px;padding-left: 40px;">
                            <el-option v-for="(item,index) in citys " :key="index" :label="item.name"
                                       :value="item.name"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="区" style="padding-left: 28px;">
                        <el-select v-model="detailData.zone" placeholder="请选择县/区"
                                   style="width: 180px; padding-left: 33px;">
                            <el-option v-for="(item,index) in districts " :key="index" :label="item.name"
                                       :value="item.name"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="地址" prop="address">
                        <el-input v-model="detailData.address" style="width: 180px;padding-left: 28px;"
                                  auto-complete="off" placeholder="只需要填写街道（村）、道路、门牌"></el-input>
                    </el-form-item>
                    <el-form-item label="项目图片" prop="img" style="padding-left: 20px;">
                        <el-input v-model="detailData.img" style="width: 180px" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="联系人" prop="manager">
                        <el-input v-model="detailData.manager" style="width: 180px;padding-left: 18px;"
                                  auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="联系电话" prop="phone" style="padding-left: 20px;">
                        <el-input v-model="detailData.phone" style="width: 180px" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="经度" prop="img">
                        <el-input v-model="detailData.lng" style="width: 180px;padding-left: 30px;"
                                  auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="纬度" prop="img" style="padding-left: 20px;">
                        <el-input v-model="detailData.lat" style="width: 180px;padding-left: 30px;"
                                  auto-complete="off"></el-input>
                    </el-form-item>
                </el-form>
            </el-card>
            <span slot="footer" class="dialog-footer">
                    <el-button style="text-align: center" @click="editFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveProject('detailData')"
                               style="text-align: center">确定</el-button>
            </span>
        </el-dialog>

        <!--管理设备界面-->
        <el-dialog
                title="管理设备"
                :visible.sync="editFormVisible1"
                width="70%"
                :before-close="handleClose1">
            <el-card>
                <el-form :inline="true" :model="this.managementData" class="demo-form-inline" ref="managementData">
                    <el-form-item label="设备序号" prop="deviceNo">
                        <el-input v-model="managementData.deviceNo" auto-complete="off" style="width:240px"
                                  placeholder="设备序号长度16位"></el-input>
                    </el-form-item>
                    <el-form-item label="设备名称" prop="Name">
                        <el-input v-model="managementData.Name" auto-complete="off" style="width:240px"
                                  placeholder="请输入设备名称"></el-input>
                    </el-form-item>
                    <el-form-item label="设备地址" prop="installAddress">
                        <el-input v-model="managementData.installAddress" auto-complete="off" style="width:240px"
                                  placeholder="请输入设备安装地址"></el-input>
                    </el-form-item>
                    <el-form-item label="电流变比" prop="IRatio">
                        <el-input v-model="managementData.IRatio" auto-complete="off" style="width:240px"
                                  placeholder="请输入电流变比"></el-input>
                    </el-form-item>
                    <el-form-item label="电压变比" prop="URatio">
                        <el-input v-model="managementData.URatio" auto-complete="off" style="width:240px"
                                  placeholder="请输入电压变比"></el-input>
                    </el-form-item>
                    <el-form-item label="漏电变比" prop="ZRatio">
                        <el-input v-model="managementData.ZRatio" auto-complete="off" style="width:240px"
                                  placeholder="请输入漏电变化"></el-input>
                        <el-button type="primary" @click="saveData('managementData')" size="mini"
                                   style="margin-left: 30px">保存
                        </el-button>
                        <el-button size="mini" @click="resetForm('managementData')">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-card>
            <br/>
            <el-card>
                <el-table
                        :data="tableDeviceData.data"
                        :stripe="true"
                        :border="true"
                        tooltip-effect="dark">

                    <el-table-column type="index" label="序号" width="50px" fixed align="center">
                    </el-table-column>
                    <el-table-column prop="projectName" label="项目名称" fixed align="center">
                    </el-table-column>
                    <el-table-column prop="deviceNo" label="设备序号" align="center">
                    </el-table-column>
                    <el-table-column prop="deviceName" label="设备名称" align="center">
                    </el-table-column>
                    <el-table-column prop="SIMcardNO" label="物联网卡号" align="center">
                    </el-table-column>
                    <el-table-column prop="IRatio" label="电流变比" align="center">
                    </el-table-column>
                    <el-table-column prop="ZRatio" label="漏电变比" align="center">
                    </el-table-column>
                    <el-table-column prop="installAddress" label="设备地址" align="center">
                    </el-table-column>
                    <el-table-column label="操作" width="180px" fixed="right" align="center">
                        <template slot-scope="scope">
                            <el-button @click="editMessage(scope.$index,scope.row)" size="mini" round
                                       icon="el-icon-edit">编辑
                            </el-button>
                            <el-button @click="collectorDelete(scope.$index,scope.row)" size="mini" round
                                       icon="el-icon-delete" type="danger">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
            <!--编辑弹出处理页面-->
            <template slot="footer">
                <div class="block">
                    <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange1"
                            :current-page.sync="currentPage1"
                            layout="prev, pager, next, jumper"
                            :total="tableDeviceData.total"
                            class="footer1"
                    >
                    </el-pagination>
                </div>
            </template>
            <span slot="footer" class="dialog-footer">
                    <el-button style="text-align: center" type="primary"
                               @click="editFormVisible1 = false">关闭</el-button>
            </span>
        </el-dialog>

        <!--管理联系人-->
        <el-dialog
                title="管理联系人"
                :visible.sync="contactVisible"
                width="50%">

            <el-card>
                <el-form :inline="true" class="demo-form-inline">
                    <el-form-item label="选择用户">
                        <el-select  placeholder="" v-model="formUser.userId" style="width: 150px;">
                            <el-option v-for="u in childUsers" :value="u.Id" :key="u.Id" :label="u.Username" ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="选择角色">
                        <el-select  placeholder="" v-model="formUser.roleId" style="width: 150px;">
                            <el-option v-for="u in roles" :value="u.roleid" :label="u.rolename" :key="u.roleid" ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button style="text-align: center" type="primary"
                                   @click="onSaveProjectUser">保存</el-button>
                    </el-form-item>
                </el-form>
            </el-card>
            <br/>
            <el-card>

                <el-table
                        :data="contactTableData"
                        :stripe="true"
                        :border="true"
                        tooltip-effect="dark">

                    <el-table-column type="index" width="50" label="序号" align="center"></el-table-column>
                    <el-table-column prop="UserName" label="姓名"  align="center">
                    </el-table-column>
                    <el-table-column prop="Telephone" label="电话"   align="center">
                    </el-table-column>
                    <el-table-column prop="" label="角色"   align="center">
                        <template slot-scope="scope">
                                <span>{{retRoleName(scope.row.Role)}}</span>
                        </template>

                    </el-table-column>
                    <el-table-column label="操作" width="180px" fixed="right" align="center">
                        <template slot-scope="scope">
                            <el-button @click="onDelProjectUser(scope.$index,scope.row)" size="mini" round
                                       icon="el-icon-delete" type="danger">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>

        </el-dialog>
    </d2-container>
</template>

<script>
    import {
        getProvinceList, getProjectTable, getSaveProject,
        getManagementData, getDeviceTable,
        getUserId, deleteProject, deleteCollector,
        getProjectUsers,getChildUsers,saveProjectUser
    } from "../../api/data/projectManagement"
    import {mapState} from 'vuex'
    import util from '@/libs/util.js'

    import{getRoleTable} from "../../api/data/getRole"

    export default {
        watch: {
            porjectNode7: function (newnode, oldnode) {
                console.log('projectnode7', newnode)

                this.user.UserId = newnode.Id
                var data = {}
                data.UserId = newnode.Id
                data.pageno = 1
                this.handleProjectTable(data, 1)
            }
        },
        created(){
            getRoleTable({pageno: 1, pagesize: 10}).then(res=>{
                this.roles = res.data;
            });

            getChildUsers().then(res=>{
                this.childUsers = res.data;
            });
        },
        computed: {
            ...mapState('d2admin/projectSelect', [
                'porjectNode7'
            ])
        },
        mounted() {
            let _this = this;
            this.handleProjectTable({}, 1);
            this.user.UserId = util.cookies.get('uuid')

            this.handlePlaceSelect('province', '中国')
            //this.handleDetailMessage();

        },
        data() {
            return {
                project: {},
                user: {},
                provices: [],
                citys: [],
                districts: [],
                username: [],

                formInline: {
                    province: '',
                    city: '',
                    zone: '',
                    projectName: '',
                    address: '',
                    owner: '',
                    DeviceNo: '',

                },
                currentPage: 1,
                currentPage1: 1,
                parentName: [],
                province: [],
                city: [],
                district: [],
                address: [],
                owner: [],
                DeviceNo: [],
                tableData: [],
                tableDeviceData: [],
                detailData: {

                    projectName: '',
                    country: '',
                    city: '',
                    zone: '',
                    address: '',
                    img: '',
                    manager: '',
                    phone: '',
                    lng: '',
                    lat: '',
                    username: ''

                },
                managementData: {
                    deviceNo: '',
                    Name: '',
                    installAddress: '',
                    IRatio: '',
                    URatio: '',
                    ZRatio: ''
                },
                editFormVisible: false,
                editFormVisible1: false,
                contactVisible:false,
                contactTableData:[],
                roles:[],
                childUsers:[],
                formUser:{
                    userId:'',
                    roleId:'',
                    projectId:''
                }

            }
        },
        methods: {
            //省市区级联
            handlePlaceSelect(level, parentName) {
                getProvinceList(level, parentName).then(res => {
                    switch (level) {
                        case 'province':
                            this.provices = res.data;
                            break;
                        case 'city':
                            this.citys = res.data;
                            break;
                        case 'district':
                            this.districts = res.data;
                            break
                    }

                });
            },
            handleProvinceSelect(value) {
                this.handlePlaceSelect('city', value);
            },
            handleCitySelect(value) {
                this.handlePlaceSelect('district', value);
            },
            //获取表格数据
            handleProjectTable(data = {}, pageno) {
                data = Object.assign(data, {pageno: pageno, pagesize: 10});
                getProjectTable(data).then(res => {
                    this.tableData = res;
                })
            },
            // 获取管理设备数据
            handleDeviceTable(data = {}, pageno) {
                data = Object.assign(data, {pageno: pageno, pagesize: 5});
                getDeviceTable(data).then(res => {
                    this.tableDeviceData = res;
                })
            },
            //搜索按钮事件
            onSubmit() {
                var data = Object.assign(this.user, this.formInline)
                this.handleProjectTable(data, 1);
            },
            //分页操作
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.handleProjectTable(this.user, val)
            },
            handleCurrentChange1(val) {
                console.log(`当前页: ${val}`);
                this.handleDeviceTable(this.user, val)
            },
            //创建项目弹出菜单
            createProject: function () {
                this.editFormVisible = true;
                console.log(this.$refs)


            },
            //提交项目
            saveProject(detailData) {
                this.$refs[detailData].validate((valid) => {
                    if (valid) {
                        var data = Object.assign(this.user, this.detailData)
                        console.log(data)
                        this.handleDetailMessage(data);
                        this.editFormVisible = false;
                        //刷新

                    } else {

                        return false;
                    }
                });
            },
            handleDetailMessage(detailData) {
                getSaveProject(detailData).then(res => {
                    if (res.state === 0) {
                        this.$message({
                            message: '提交成功！',
                            type: 'success'
                        });
                        var data = {}
                        data.UserId = this.user.UserId

                        this.handleProjectTable(data, this.currentPage)
                    } else {
                        this.$message({
                            message: '提交失败！',
                            type: 'error'
                        });

                    }
                });
            },
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {
                    });
            },
            handleClose1(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {
                    });
            },
            //编辑项目信息
            edit: function (index, row) {
                this.editFormVisible = true;
                this.detailData = row
                this.project = row
            },
            //管理设备信息
            addDevice: function (index, row) {
                this.editFormVisible1 = true;

                this.project = row
                this.handleDeviceTable(this.project, 1);

            },

            //设备保存按钮
            saveData(managementData) {
                this.$refs[managementData].validate((valid) => {
                    if (valid) {
                        //this.detailData.projectNo=this.project.projectNo;
                        this.managementData.ProjectNo = this.project.projectNo
                        console.log("添加设备", this.managementData)
                        getManagementData(this.managementData).then(res => {
                            if (res.state === 0) {
                                this.$message({
                                    message: '提交成功！',
                                    type: 'success'
                                });
                                this.editFormVisible = false;
                                this.handleDeviceTable(this.project, 1);
                                //清空本次修改的form表单
                                this.$refs[managementData].resetFields();
                            }
                        })

                    } else {
                        this.$message({
                            message: '提交失败！',
                            type: 'error'
                        });
                        return false;
                    }
                });
            },
            //
            // //提交数据
            // handleManagementData(managementData) {
            //     getManagementData(managementData).then(res => {
            //         if (res.state === 0) {
            //             this.$message({
            //                 message: '提交成功！',
            //                 type: 'success'
            //             });
            //         } else {
            //             this.$message({
            //                 message: '提交失败！',
            //                 type: 'error'
            //             });
            //
            //         }
            //     });
            // },
            //编辑按钮提交数据给表单
            editMessage: function (index, data) {
                this.editFormVisible1 = true;
                console.log(data);
                data.Name = data.deviceName
                this.managementData = data;
            },
            //重置按钮
            resetForm(managementData) {
                this.$refs[managementData].resetFields();
            },
            //删除操作
            handleDelete: function (index, row) {
                this.$confirm('此操作将永久删除项数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleteProject(row).then(res => {
                        if (res.state === 0) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.handleProjectTable(this.user, 1)
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //diango删除按钮
            collectorDelete: function (index, row) {
                this.$confirm('此操作将永久删除项数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    row.DeviceNo = row.deviceNo
                    deleteCollector(row).then(res => {
                        if (res.state === 0) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.handleDeviceTable(this.project, 1)
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            //管理联系人
            onContact:function(index,row){
                this.contactVisible = true;
                this.formUser.projectId = row.Id;
                getProjectUsers(row.Id).then(res=>{
                    this.contactTableData = res.data;
                });
            },

            retRoleName:function(id){

                for(let r of this.roles){
                    if(r.roleid==id){
                        return r.rolename;
                    }
                }
                return "";
            },
            onSaveProjectUser:function(){

                let datas = [...this.contactTableData];
                datas.push({
                    UserId:this.formUser.userId,
                    Role:this.formUser.roleId
                });

                let userids = datas.map(u=>u.UserId).join();
                let roles = datas.map(u=>u.Role).join();

                saveProjectUser(
                    this.formUser.projectId,
                    userids,
                    roles).then(res=>{
                    getProjectUsers(this.formUser.projectId).then(res=>{
                        this.contactTableData = res.data;
                    });
                });
            },
            onDelProjectUser:function(index,row){
                let datas = [...this.contactTableData];
                datas.splice(index,1);
                let userids = datas.map(u=>u.UserId).join();
                let roles = datas.map(u=>u.Role).join();

                saveProjectUser(
                    this.formUser.projectId,
                    userids,
                    roles).then(res=>{
                    getProjectUsers(this.formUser.projectId).then(res=>{
                        this.contactTableData = res.data;
                    });
                });
            },

        }
    }

</script>

<style scoped>
    .el-table .cell, .el-table th div {
        margin-left: 0px;
    }

    .el-button {
        padding: 10px 15px;
        margin-right: 0px;
    }

    .footer1 {
        text-align: left !important;
    }

    .minis{
        padding: 2px;
    }


</style>
